package com.geovis.emergency.spd.biz.system.wrapper;

import cn.hutool.core.util.StrUtil;
import com.geovis.emergency.spd.entity.system.pojo.node.INode;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Maps;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class ForestNodeManager<T extends INode<T>> {
    private final ImmutableMap<String, T> nodeMap;
    private final Map<String, Object> parentIdMap = Maps.newHashMap();

    public ForestNodeManager(List<T> nodes) {
        this.nodeMap = Maps.uniqueIndex(nodes, INode::getId);
    }

    public INode<T> getTreeNodeAt(String id) {
        return this.nodeMap.containsKey(id) ? (INode)this.nodeMap.get(id) : null;
    }

    public void addParentId(String parentId) {
        this.parentIdMap.put(parentId, "");
    }

    public List<T> getRoot() {
        List<T> roots = new ArrayList();
        this.nodeMap.forEach((key, node) -> {
            if (StrUtil.isBlank(node.getParentId()) || this.parentIdMap.containsKey(node.getId())) {
                roots.add(node);
            }

        });
        return roots;
    }
}